import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import '../models/git_tree_item.dart';
import '../models/git_branch.dart';
import '../services/api_service.dart';
import '../screens/file_detail_screen.dart';
import 'git_log_screen.dart';

class RepoDetailScreen extends StatefulWidget {
  final String owner;
  final String repo;
  final String sha;
  final String? initialPath;
  final bool isRoot;

  const RepoDetailScreen({
    Key? key,
    required this.owner,
    required this.repo,
    required this.sha,
    this.initialPath,
    this.isRoot = false,
  }) : super(key: key);

  @override
  State<RepoDetailScreen> createState() => _RepoDetailScreenState();
}

class _RepoDetailScreenState extends State<RepoDetailScreen> {
  final ApiService _apiService = ApiService();
  List<GitTreeItem> _items = [];
  List<GitBranch> _branches = [];
  bool _isLoading = true;
  String _currentPath = '';
  String _currentSha = '';
  String _currentCommitMsg = '';
  String _currentBranchName = '';

  @override
  void initState() {
    super.initState();
    _currentSha = widget.sha;
    Logger().d(_currentSha);
    _currentPath = widget.initialPath ?? '';
    _loadTree();
    if (widget.isRoot) {
      _loadBranches();
    }
  }

  Future<void> _loadTree() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final items = await _apiService.getRepoTree(
        owner: widget.owner,
        repo: widget.repo,
        sha: _currentSha,
      );

      items.sort((a, b) {
        if (a.type != b.type) {
          return a.type == 'tree' ? -1 : 1;
        }
        return a.path.compareTo(b.path);
      });

      setState(() {
        _items = items;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载失败: $e')),
      );
    }
  }

  Future<void> _loadBranches() async {
    try {
      final branches = await _apiService.getRepoBranches(
        owner: widget.owner,
        repo: widget.repo,
      );
      setState(() {
        _branches = branches;
        _currentCommitMsg = branches.first.commit.commit.message;
        Logger().d(_currentCommitMsg);
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载分支失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(_currentPath.isEmpty ? widget.repo : _currentPath),
          actions: [
            if (widget.isRoot)
              PopupMenuButton<GitBranch>(
                onSelected: (GitBranch branch) {
                  setState(() {
                    _currentSha = branch.commit.sha;
                    _currentBranchName = branch.name; // 保存分支名
                    _currentPath = '';
                    _currentCommitMsg = branch.commit.commit.message;
                  });
                  _loadTree();
                },
                itemBuilder: (BuildContext context) => _branches.map((branch) {
                  return PopupMenuItem<GitBranch>(
                    value: branch,
                    child: Row(
                      children: [
                        Text(branch.name),
                        if (branch.protected)
                          const Padding(
                            padding: EdgeInsets.only(left: 8.0),
                            child: Icon(Icons.lock, size: 14),
                          ),
                      ],
                    ),
                  );
                }).toList(),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    children: [
                      Text(_currentBranchName.isEmpty
                          ? _currentSha
                          : _currentBranchName),
                      const Icon(Icons.arrow_drop_down),
                    ],
                  ),
                ),
              ),
          ],
        ),
        body: Column(children: [
          if (widget.isRoot) // 添加 commit message 横幅
            ListTile(
              title: Text(
                _currentCommitMsg,
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.black87,
                ),
              ),
              tileColor: Colors.blueGrey[50],
              contentPadding: const EdgeInsets.fromLTRB(12, 1, 12, 1),
              trailing: IconButton(
                icon: const Icon(Icons.more_horiz),
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => GitLogScreen(
                                widget.owner,
                                widget.repo,
                                _currentSha,
                              )));
                },
              ),
            ),
          Expanded(
            child: _isLoading
                ? const Center(child: CircularProgressIndicator())
                : ListView.builder(
                    itemCount: _items.length,
                    itemBuilder: (context, index) {
                      final item = _items[index];
                      return ListTile(
                        leading: Icon(
                          item.type == 'tree'
                              ? Icons.folder
                              : Icons.insert_drive_file,
                          color: item.type == 'tree'
                              ? Colors.amber
                              : Colors.blueGrey,
                        ),
                        title: Text(item.path),
                        subtitle: item.type == 'blob'
                            ? Text(formatSize(item.size)) // 使用新方法格式化大小
                            : null,
                        trailing: item.type == 'tree'
                            ? const Icon(Icons.chevron_right)
                            : null,
                        onTap: () {
                          if (item.type == 'tree') {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => RepoDetailScreen(
                                  owner: widget.owner,
                                  repo: widget.repo,
                                  sha: item.sha,
                                  initialPath: item.path,
                                ),
                              ),
                            );
                          } else {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => FileDetailScreen(
                                  owner: widget.owner,
                                  repo: widget.repo,
                                  sha: item.sha,
                                  fileName: item.path,
                                ),
                              ),
                            );
                          }
                        },
                      );
                    },
                  ),
          )
        ]));
  }

  String formatSize(int bytes) {
    if (bytes < 1024) return '$bytes B';
    final kb = bytes / 1024;
    return kb < 1024
        ? '${kb.toStringAsFixed(1)} KB'
        : '${(kb / 1024).toStringAsFixed(1)} MB';
  }
}
